package com.yc.cinema.proxy;

import com.yc.cinema.designpatterm.proxy.saticpy.AllTeacher;
import com.yc.cinema.designpatterm.proxy.saticpy.MusicTeacher;
import com.yc.cinema.designpatterm.proxy.saticpy.TeacherProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理
 * Proxy
 * InvocationHandler
 */
public class JDKProxy {

    public static void main(String[] args) {
        /**
         * 静态代理
         */
        MusicTeacher musicTeacher = new MusicTeacher();
        TeacherProxy teacherProxy = new TeacherProxy(musicTeacher);
        //调代理对象方法
        teacherProxy.teach();

        System.out.println("-------------------------------");
        /**
         * jdk动态代理
         */
        AllTeacher proxyTeacher = proxy(musicTeacher);
        proxyTeacher.teach();


    }

    public static <T> T proxy(T t){
        T ret = (T) Proxy.newProxyInstance(
                t.getClass().getClassLoader(), // 类加载器
                t.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("开始代理...");
                        System.out.println("教语文");
                        Object ret = method.invoke(t, args);
                        System.out.println("代理结束...");
                        return ret;
                    }
                });
        return ret;
    }

}
